<template>
  <div class="personal-container">
    <div class="profile-card">
      <div class="profile-header">
        <div class="avatar-container">
          <img :src="userInfo.avatar || 'https://via.placeholder.com/150'" alt="Avatar" class="avatar-img">
          <div class="user-name">{{ userInfo.userName }}</div>
          <el-button type="primary" size="small" @click="handleEdit" class="edit-btn">
            <i class="el-icon-edit"></i> 编辑资料
          </el-button>
        </div>
      </div>
      
      <div class="info-cards">
        <div class="info-card">
          <div class="icon-wrapper blue">
            <i class="el-icon-user"></i>
          </div>
          <div class="info-content">
            <div class="label">性别</div>
            <div class="value">{{ userInfo.sex }}</div>
          </div>
        </div>
        
        <div class="info-card">
          <div class="icon-wrapper green">
            <i class="el-icon-office-building"></i>
          </div>
          <div class="info-content">
            <div class="label">职业</div>
            <div class="value">{{ userInfo.occupation }}</div>
          </div>
        </div>
        
        <div class="info-card">
          <div class="icon-wrapper purple">
            <i class="el-icon-location"></i>
          </div>
          <div class="info-content">
            <div class="label">地址</div>
            <div class="value">{{ userInfo.address }}</div>
          </div>
        </div>
      </div>

      <div class="additional-info">
        <el-card class="info-section">
          <template #header>
            <div class="card-header">
              <span>个人简介</span>
            </div>
          </template>
          <div class="bio-content">
            {{ userInfo.bio || '这个人很懒，还没有填写简介' }}
          </div>
        </el-card>
      </div>
    </div>

    <!-- 编辑个人信息对话框 -->
    <el-dialog 
      title="编辑个人信息" 
      v-model="dialogVisible" 
      width="50%"
      :close-on-click-modal="false"
    >
      <el-form :model="editForm" ref="editFormRef" :rules="rules" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.userName"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="editForm.sex" placeholder="请选择性别">
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="职业" prop="occupation">
          <el-input v-model="editForm.occupation"></el-input>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="editForm.address"></el-input>
        </el-form-item>
        <el-form-item prop="cover" label="封面图片">
          <el-upload
            action="http://localhost:9090/api/file/cover"
            ref="coverUpload"
            :data="getUploadData"
            :before-upload="beforeCoverUpload"
            @success="handleImgUploadSuccess"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="个人简介" prop="bio">
          <el-input type="textarea" v-model="editForm.bio" :rows="4"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue';
import request from "@/utils/request";
import { ElMessage } from "element-plus";

// 用户信息
const userInfo = ref({});
const dialogVisible = ref(false);
const editFormRef = ref(null);
const username = localStorage.getItem('userName')
const NewCover=ref("");
const NewName=ref("")


const getUploadData = () => {
  console.log(NewName.value,"====");
  return {
    name: NewName.value, // Dynamic value of name
  };

};
const beforeCoverUpload = async () => {
  // 在上传新图片之前，先删除原有图片
  await deleteOldImage(); // 调用删除原有图片的方法
  // 继续上传新图片
  return true;
};

const deleteOldImage = async () => {
  try {
    // 假设你从后端获取了原有图片的URL
    const cover =NewCover.value
    console.log(cover,"===");
    // 发送请求删除原有图片
    await request.post('/file/coverOne', { params: { cover: cover } });
    console.log("原有图片删除成功");
 
  } catch (error) {
    console.error("原有图片删除失败", error);
  }
};
const handleImgUploadSuccess = (response) => {
  editForm.avatar = response;
  console.log("img--",response);
};


// 编辑表单数据
const editForm = reactive({
  username: '',
  age: '',
  occupation: '',
  address: '',
  avatar: '',
  bio: ''
});

// 表单验证规则
const rules = {
  userName: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  sex: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  occupation: [
    { required: true, message: '请输入职业', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请输入地址', trigger: 'blur' }
  ]
};

// 获取用户信息
const getUserInfo = async () => {
  try {
    const res = await request.get(`/user/username/${username}`);
    if (res.data.code === '200') {
      userInfo.value = res.data.data;
    } else {
      ElMessage.error('获取用户信息失败');
    }
  } catch (error) {
    console.error('获取用户信息错误:', error);
    ElMessage.error('获取用户信息失败');
  }
};

// 打开编辑对话框
const handleEdit = () => {
  NewCover.value=userInfo.value.avatar
  Object.assign(editForm, userInfo.value);
  console.log('==',userInfo.value.avatar);
  dialogVisible.value = true;
};

// 提交表单
const submitForm = async () => {
  if (!editFormRef.value) return;
  
  await editFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const res = await request.post('/user/edit', editForm);
        if (res.data.code === '200') {
          ElMessage.success('更新成功');
          dialogVisible.value = false;
          getUserInfo(); // 重新获取用户信息
        } else {
          ElMessage.error(res.data.msg || '更新失败');
        }
      } catch (error) {
        console.error('更新用户信息错误:', error);
        ElMessage.error('更新失败');
      }
    }
  });
};

// 页面加载时获取用户信息
onMounted(() => {
  getUserInfo();
});
</script>

<style scoped>
.personal-container {
  padding: 20px;
  min-height: 100vh;
  background: #f5f7fa;
}

.profile-card {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
}

.profile-header {
  text-align: center;
  margin-bottom: 40px;
}

.avatar-container {
  position: relative;
  display: inline-block;
}

.avatar-img {
  width: 150px;
  height: 150px;
  border-radius: 50%;
  border: 4px solid #fff;
  box-shadow: 0 2px 15px rgba(0,0,0,0.1);
  transition: transform 0.3s ease;
}

.avatar-img:hover {
  transform: scale(1.05);
}

.user-name {
  margin-top: 15px;
  font-size: 24px;
  font-weight: bold;
  color: #2c3e50;
}

.info-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.info-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  display: flex;
  align-items: center;
  box-shadow: 0 2px 12px rgba(0,0,0,0.08);
  transition: transform 0.3s ease;
}

.info-card:hover {
  transform: translateY(-5px);
}

.icon-wrapper {
  width: 50px;
  height: 50px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
}

.icon-wrapper i {
  font-size: 24px;
  color: white;
}

.blue {
  background: linear-gradient(135deg, #409EFF, #3a8ee6);
}

.green {
  background: linear-gradient(135deg, #67C23A, #5daf34);
}

.purple {
  background: linear-gradient(135deg, #9B59B6, #8E44AD);
}

.info-content {
  flex: 1;
}

.label {
  font-size: 14px;
  color: #909399;
  margin-bottom: 5px;
}

.value {
  font-size: 16px;
  color: #2c3e50;
  font-weight: 500;
}

.additional-info {
  margin-top: 30px;
}

.info-section {
  border-radius: 12px;
  overflow: hidden;
}

.card-header {
  font-size: 18px;
  font-weight: bold;
  color: #2c3e50;
}

.bio-content {
  padding: 20px 0;
  line-height: 1.6;
  color: #5a6a7f;
}

@media (max-width: 768px) {
  .info-cards {
    grid-template-columns: 1fr;
  }
  
  .profile-card {
    padding: 10px;
  }
}

.edit-btn {
  position: absolute;
  right: -60px;
  top: 50%;
  transform: translateY(-50%);
}

.dialog-footer {
  text-align: right;
  margin-top: 20px;
}

.el-input-number {
  width: 100%;
}
</style>
  